package com.cxb.oauth2.config;

import com.sun.xml.internal.ws.api.model.CheckedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(getUserDetails());

//        auth.inMemoryAuthentication()
//                .withUser("jk").password(passwordEncoder.encode("jkjk")).roles("USER")
//                .and()
//                .withUser("admin").password(passwordEncoder.encode("admin123")).roles("ADMIN");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/tokens/**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().csrf().disable();
    }

    public UserDetailsService getUserDetails() {
        return (String userName) -> {
            if (userName.equals("admin")) {
                System.out.println(passwordEncoder.encode("admin123"));
                return User.withUsername(userName).authorities("TEST").password(passwordEncoder.encode("admin123")).build();
            }
            if (userName.equals("jk")) {
                System.out.println(passwordEncoder.encode("jkjk"));
                return User.withUsername(userName).authorities("TEST").password(passwordEncoder.encode("jkjk")).build();
            }
            throw new UsernameNotFoundException("no user");
        };
    }
}


